//
//  RegisterViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/9/19.
//

import UIKit
import YYKit
import RxSwift

class RegisterViewController: BaseViewController {
    private var welcomeLab: UILabel!
    private var titleLab: UILabel!
    private var phoneView: KInputTextField!
    private var protocolLab: YYLabel!
    private var agreeBtn: UIButton!
    private var getCodeBtn: UIButton!
    private var overView: WBPopOverView?
    private var areaCodeBtn: UIButton!
    private var select: Bool = false
    private var phoneAreaList: [PhoneAreaObj] = [] //手机区号
    ///登录页传过来的手机号
    var phone: String = ""
    var disBag = DisposeBag()
    
    var dataModel = UserInfoObj()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.barBackgroundColor = .white
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        welcomeLab = UILabel()
        welcomeLab.textColor = Theme.titleLabColor
        welcomeLab.backgroundColor = UIColor.clear
        welcomeLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        welcomeLab.numberOfLines = 1
        welcomeLab.lineBreakMode = .byTruncatingTail
        welcomeLab.text = MMLocalizedString("regist_wel", comment: "欢迎成为")
        view.addSubview(welcomeLab)
        
        titleLab = UILabel()
        titleLab.textColor = Theme.mainColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 26)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.text = MMLocalizedString("regist_vip", comment: "Kool Car 会员")
        view.addSubview(titleLab)
        
        //账号
        phoneView = KInputTextField.init(frame: .zero)
        phoneView.textField.keyboardType = .numberPad
        phoneView.placeholder = MMLocalizedString("regist_please_enter_phone", comment: "请输入手机号码")
        self.view.addSubview(phoneView)
        
        areaCodeBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 60, height: 54))
        areaCodeBtn.setup_titleColor(color: Theme.titleLabColor)
        var tempCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        if tempCode == "" {
            let codeObj = XTManageCenter.getPhoneAreaCodeList().first
            tempCode = codeObj?.code ?? "852"
        }
        areaCodeBtn.setup_titleLabel(text: tempCode)
        areaCodeBtn.setup_image(image: UIImage.init(named: "icon_drop_full"))
        areaCodeBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        areaCodeBtn.semanticContentAttribute = .forceRightToLeft
        areaCodeBtn.backgroundColor = .white
        areaCodeBtn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 5)
        areaCodeBtn.addTarget(self, action: #selector(self.areaCodeBtnAction), for: .touchUpInside)
        phoneView.leftView = areaCodeBtn

        //同意条款
        agreeBtn = UIButton()
        agreeBtn.setup_image(image: UIImage.init(named: "icon_check"))
        agreeBtn.addTarget(self, action: #selector(agreeBtnAction), for: .touchUpInside)
        view.addSubview(agreeBtn)
        
        //阅读条款
        protocolLab = YYLabel(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 40))
        protocolLab.numberOfLines = 0
        protocolLab.textAlignment = .center
        self.view.addSubview(protocolLab)
        
        //获取验证码
        getCodeBtn = UIButton()
        getCodeBtn.setup_titleLabel(text: MMLocalizedString("forget_get_code", comment: "获取验证码"))
        getCodeBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        getCodeBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        getCodeBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        getCodeBtn.layer.cornerRadius = 8
        getCodeBtn.layer.masksToBounds = true
        getCodeBtn.setup_titleColor(color: .white)
        getCodeBtn.addTarget(self, action: #selector(getCodeBtnAction), for: .touchUpInside)
        view.addSubview(getCodeBtn)
        
        self.initailValue()
        self.bindMVVM()
        self.addSnpLayout()
        self.getPhoneAreaList()
    }
  
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    private func initailValue(){
        self.phoneView.textField.text = self.phone
        let privacy  = MMLocalizedString("regist_private", comment: "隐私条款")
        let service = MMLocalizedString("regist_protocol", comment: "法律声明")
        let str = String(format: MMLocalizedString("regist_agree", comment: "已阅读并同意%@和%@"), service, privacy)
        let serviceLoc = str.findSubStringLocation(subString: service)
        let privacyLoc = str.findSubStringLocation(subString: privacy)
        
        let attStr = NSMutableAttributedString.init(string: str)
        attStr.lineSpacing = 8
        attStr.setTextHighlight(NSRange.init(location: 0, length: str.count), color: Theme.line8Color, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
        })
        
        if serviceLoc > 0 {
            attStr.setTextHighlight(NSRange.init(location: serviceLoc, length: service.count), color: Theme.mainColor, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
                self.didTapProtocoAction()
            })
        }
        
        if privacyLoc > 0 {
            attStr.setTextHighlight(NSRange.init(location: privacyLoc, length: privacy.count), color: Theme.mainColor, backgroundColor: UIColor.clear, tapAction: { (containerView, attr, tRange, rect) in
                self.didTapPrivateAction()
            })
        }
        self.protocolLab.attributedText = attStr
    }
    
    private func addSnpLayout(){
        welcomeLab.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.top.equalTo(NavBarHight+60)
        }
        
        titleLab.snp.makeConstraints { make in
            make.top.equalTo(welcomeLab.snp.bottom).offset(14)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
        phoneView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(titleLab.snp.bottom).offset(40)
            make.height.greaterThanOrEqualTo(54)
        }
        
        agreeBtn.snp.makeConstraints { make in
            make.left.equalTo(26)
            make.top.equalTo(phoneView.snp.bottom).offset(10)
            make.height.greaterThanOrEqualTo(30)
            make.width.equalTo(30)
        }
        
        protocolLab.snp.makeConstraints { make in
            make.left.equalTo(agreeBtn.snp.right)
            make.top.equalTo(phoneView.snp.bottom).offset(10)
            make.right.equalTo(-30)
            make.height.greaterThanOrEqualTo(30)
        }
        
        getCodeBtn.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(protocolLab.snp.bottom).offset(96)
            make.height.equalTo(46)
        }
    }
    
    private func bindMVVM(){
        self.phoneView.textField.rx.text.orEmpty.subscribe { txt in
            self.phone = txt.element ?? ""
        }.disposed(by: self.disBag)
        self.phoneView.textField.sendActions(for: .allEvents)
    }
    
    private func getPhoneAreaList(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.commonMemberAreaCode(param: [:]), objectType: PhoneAreaResModel.self) { data in
            let resultObj = data as? PhoneAreaResModel
            guard resultObj?.code == "1" else {
                self.phoneAreaList = [PhoneAreaObj.init(code: "852")]
                self.setDefaultAreaCode()
                return
            }
            
            let codeJson = resultObj?.data?.areaCode ?? ""
            var codeList = [PhoneAreaCodeModel].init(JSONString: codeJson) ?? []
            
            if codeList.count == 0 {
                //默认852
                self.phoneAreaList = [PhoneAreaObj.init(code: "852")]
            }else  if codeList.count == 1 {
                let code = codeList.first?.areacode ?? "852"
                self.phoneAreaList = [PhoneAreaObj.init(code: code)]
            }else {
                codeList = codeList.sorted(by: { res1, res2 in
                    return res1.order ?? "852" < res2.order ?? "852"
                })
                
                self.phoneAreaList = []
                codeList.forEach { tempItem in
                    let item = PhoneAreaObj.init(code: tempItem.areacode ?? "")
                    self.phoneAreaList.append(item)
                }
            }
            self.setDefaultAreaCode()
        } error: { err in
            //默认852
            self.phoneAreaList = [PhoneAreaObj.init(code: "852")]
            self.setDefaultAreaCode()
        }
    }
    
    ///默认codeArea
    private func setDefaultAreaCode(){
        let code = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        if code == "" {
            let tempCode = self.phoneAreaList.first?.code ?? ""
            self.areaCodeBtn.setup_titleLabel(text: tempCode)
            XTManageCenter.setLocalDataString(aKey: UtilCenter.phoneCodeKey, aValue: tempCode)
        }
    }
    
    ///区号选择
    @objc func areaCodeBtnAction(){
        self.closeKeyboard()
        let vc = PhoneAreaPickerVC()
        vc.dataArray = self.phoneAreaList
        vc.modalPresentationStyle = .overFullScreen
        vc.callBack = { [weak self] codeObj in
            self?.areaCodeBtn.setup_titleLabel(text: codeObj.code)
            XTManageCenter.setLocalDataString(aKey: UtilCenter.phoneCodeKey, aValue: codeObj.code)
        }
        self.present(vc, animated: false)
    }
    
    ///法律声明
    private func didTapProtocoAction(){
        self.closeKeyboard()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.indexLegalStatement, objectType: ProtocolResData.self) { data in
            let resultObj = data as? ProtocolResData
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            let vc = WebViewController()
            vc.localHtmlStr = resultObj?.data?.content ?? ""
            vc.titleStr = MMLocalizedString("launch_protocol", comment: "法律声明")
            self.navigationController?.pushViewController(vc, animated: true)
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///隐私条款
    ///http://localhost:6100/cloud/common/index/privacyGreement
    private func didTapPrivateAction(){
        self.closeKeyboard()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.privacyGreement(param: [:]), objectType: ProtocolResData.self) { data in
            let resultObj = data as? ProtocolResData
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            let vc = WebViewController()
            vc.localHtmlStr = resultObj?.data?.content ?? ""
            vc.titleStr = MMLocalizedString("launch_private", comment: "隐私条款")
            self.navigationController?.pushViewController(vc, animated: true)
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    @objc func agreeBtnAction(){
        self.closeKeyboard()
        self.overView?.dismiss()
        self.select = !self.select
        if self.select {
            agreeBtn.setup_image(image: UIImage.init(named: "icon_agree"))
        }else{
            agreeBtn.setup_image(image: UIImage.init(named: "icon_check"))
        }
    }
    
    ///关键盘
    private func closeKeyboard(){
        self.phoneView.textField.resignFirstResponder()
    }
    
    ///获取验证码step1: 判断手机号是否存在
    @objc func getCodeBtnAction(){
        
        self.closeKeyboard()
        if self.phone == "" {
            self.phoneView.warnText = MMLocalizedString("regist_please_enter_phone", comment: "请输入手机号码")
            return
        }
        
        //是否同意
        if !select {
            self.showPopView()
            return
        }
        
        //校验手机号
        let isPhone = XTManageCenter.judgeTextIsPhoneNumber(text: self.phone)
        if !isPhone {
            self.phoneView.warnText = MMLocalizedString("regist_please_enter_real_phone", comment: "请输入正确的手机号码")
            return
        }
        let param: [String: String] = ["phone": self.phone,
                                       "type":"1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.commonMmemberVerify(param: param), objectType: CommondResModel.self) { data in
            let resultObj = data as? CommondResModel
            if resultObj?.code == "11" {
                //账号已注册
                self.showTipAlert()
                return
            }
            
            guard resultObj?.code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            //未注册,去获取验证码
            self.fetchGetSMSCode()
        } error: { err in
            
        }
        
    }
    
    ///获取验证码step2: 请求验证码
    private func fetchGetSMSCode(){
     
        self.view.showLoadingHUDText()
        let areaCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        let param: [String: String] = ["mobileAreaCode": areaCode,
                                       "phone": self.phone,
                                       "sendType": "1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.captchaGetCode(param: param), objectType: SMSCodeModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? SMSCodeModel
            if resultObj?.code == "1" {
                self.jumpToVerify()
//                XTAlertView.showAlertView(title: "当前验证码", message: resultObj?.data ?? "", cancelButtonTitle: "确定") { alertView, buttonIndex in
//                    self.jumpToVerify()
//                }
            }else if resultObj?.code == "10" {
                self.showTipAlert()
            }else{
                self.view.makeToast(message: resultObj?.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///号码已注册过提示
    private func showTipAlert(){
        KCarAlertView.showAlertView(title: MMLocalizedString("add_tip", comment: "提示"), message: MMLocalizedString("regist_phone_exist", comment: "该号码已注册"), cancelButtonTitle: MMLocalizedString("add_back", comment: "返回")) { buttonIndex in
            //
        }
    }
    
    ///获取验证码成功，跳转填写验证码
    private func jumpToVerify(){
        let vc = InputVerifyViewController()
        vc.pageType = .regist
        vc.phoneStr = self.phone
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    ///请勾选同意
    private func showPopView(){
        //获取labede的坐标在整个view上的位置
        var point = self.agreeBtn.center
        point = CGPoint.init(x: point.x, y: point.y + 4)
        
        let tipLab = UILabel(frame: CGRect(x: 14, y: 10, width: kScreenWidth*2/3 - 24, height: 100))
        tipLab.text = MMLocalizedString("regist_agree_first", comment: "请阅读并同意隐私条款和法律声明")
        tipLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        tipLab.textColor = Theme.whiteColor
        tipLab.numberOfLines = 0
        tipLab.lineBreakMode = .byTruncatingTail
        tipLab.sizeToFit()
        
        var tempW = tipLab.frame.size.width + 28
        if tempW > kScreenWidth * 2/3 {
            tempW = kScreenWidth * 2/3
        }
        
        if tempW < 120 {
            tempW = 120
        }
        if self.overView != nil {
            self.overView = nil
        }
        overView = WBPopOverView.init(origin: point, width: tempW, height: Float(tipLab.frame.size.height) + 20, direction: WBArrowDirection.up1)
        overView?.backgroundColor = UIColor.init(hex: 0xffffff, alpha: 0.1)
        overView?.backView.backgroundColor = Theme.titleLabColor
        overView?.backView.layer.masksToBounds = true
        overView?.backView.layer.cornerRadius = 4
        overView?.backView.addSubview(tipLab)
        overView?.pop()
    }
}
